package com.cdn.nodes.netty.handler;

import com.alibaba.fastjson2.JSONObject;
import com.cdn.common.redis.service.RedisService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Component
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Resource
    private RedisService redisService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg == null) {
            System.err.println("Received null message.");
            return;
        }

        // 解析消息
        String message = (String) msg;
        JSONObject jsonObject = JSONObject.parseObject(message);

        // 提取字段并进行非空检查
        Long nodeId = jsonObject.getLong("nodeId");
        if (nodeId == null) {
            System.err.println("Node ID is missing or invalid.");
            return;
        }

        BigDecimal cpu = jsonObject.getBigDecimal("cpu");
        BigDecimal memory = jsonObject.getBigDecimal("memory");
        Long downstreamBandwidth = jsonObject.getLong("downstreamBandwidth");
        Integer connections = jsonObject.getInteger("connections");
        BigDecimal load = jsonObject.getBigDecimal("load");

        // 创建一个新的JSONObject来存储节点数据
        JSONObject nodeData = new JSONObject();
        nodeData.put("cpu", cpu != null ? cpu : BigDecimal.ZERO);  // 使用默认值处理null
        nodeData.put("memory", memory != null ? memory : BigDecimal.ZERO);  // 使用默认值处理null
        nodeData.put("downstreamBandwidth", downstreamBandwidth != null ? downstreamBandwidth : 0L);  // 默认值处理
        nodeData.put("connections", connections != null ? connections : 0);  // 默认值处理
        nodeData.put("load", load != null ? load : BigDecimal.ZERO);  // 默认值处理

        // 将节点数据存入Redis缓存，以nodeId为key
        String key = "node:" + nodeId; // 构建Redis缓存的key
        try {
            redisService.setCacheObject(key, nodeData);  // 存储节点数据
            System.out.println("节点数据已成功存入Redis，key: " + key);

            // 将 nodeId 添加到 Redis 集合 "nodeIds"
            redisTemplate.opsForSet().add("nodeIds", nodeId.toString());
            System.out.println("节点ID已成功添加到 Redis 集合 'nodeIds'，nodeId: " + nodeId);
        } catch (Exception e) {
            System.err.println("存入Redis时出错: " + e.getMessage());
            e.printStackTrace();
        }


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 异常处理
        cause.printStackTrace();
        ctx.close();
    }

}
